const { TimeRange } = require('../util')

const filterByTimeRange = (arr, timeRange) => {
  return arr.filter(item => {
    const createdAt = item.get('createdAt').getTime()
    const start = timeRange[0].getTime()
    const end = timeRange[1].getTime()
    return createdAt >= start && createdAt <= end
  })
}

Parse.Cloud.define('getQlCounts', async (req, res) => {
  const RECENTDAY = 30
  const timeRange = new TimeRange() // 时间段
  const lastThirtyDay = timeRange.currentDays(RECENTDAY)
  const findOrderTotal = new Parse.Query('QlVip').ascending('money').find()
  const findRecentOrderCount = new Parse.Query('QlOrderCount').greaterThanOrEqualTo('createdAt', lastThirtyDay[0]).lessThanOrEqualTo('createdAt', lastThirtyDay[1]).find()
  const findUseTotalCount = new Parse.Query('QlUseTotalCount').first()
  const findRecentUseCount = new Parse.Query('QlUseCount').greaterThanOrEqualTo('createdAt', lastThirtyDay[0]).lessThanOrEqualTo('createdAt', lastThirtyDay[1]).find()

  const orderTotal = await findOrderTotal
  const recentOrderCount = await findRecentOrderCount
  const useTotalCount = await findUseTotalCount
  const recentUseCount = await findRecentUseCount

  const times = {
    thisDay: timeRange.thisDay(),
    lastDay: timeRange.lastDay(),
    beforeYesterday: timeRange.recentRange(2, 1),
    lastSevenDay: timeRange.currentDays(7),
    lastThirtyDay
  }

  const orderCount = {}
  const useCount = {}
  const useTypeMap = {install: '安装统计', use: '使用统计', 'try': '试用统计'}

  Object.keys(useTypeMap).forEach(k => {
    useCount[k] = {
      name: useTypeMap[k],
      total: useTotalCount ? useTotalCount.get(k) : 0
    }
  })

  orderTotal.forEach((item) => {
    orderCount[item.id] = {
      name: item.get('name'),
      total: item.get('buyCount') || 0,
      money: item.get('money')
    }
  })

  Object.keys(times).forEach((k) => {

    const orders = filterByTimeRange(recentOrderCount, times[k])
    orders.reduce((prev, cur) => {
      const id = cur.get('vip').id
      const count = prev[id]
      count[k] = (count[k] || 0) + (cur.get('total') || 0)
      return prev
    }, orderCount)

    const uses = filterByTimeRange(recentUseCount, times[k])
    uses.forEach((item) => {
      Object.keys(useTypeMap).forEach(type => {
        const current = useCount[type]
        current[k] = (current[k] || 0) + (item.get(type) || 0)
      })
    })
  })

  res.success({
    orderCount: Object.values(orderCount),
    useCount: Object.values(useCount)
  })
})
